<template>
	<div class="ingringr-detail-page">
		<div class="ingringr-cont page-cont-box">
			<BreadCrumb :data="dataObj.crumbList" />
			
			<div class="cont-box">
				<div class="top-box">
					<div class="condition-box">
						<div class="condition-left">
							<CombinationSearch
								:searchObjList="searchObjList.searchObjArr"
								@removeSearchCond="removeSearchCond"
								@addSearchCond="addSearchCond"
								@reset="reset"
								@searchResult="searchResult"
								@searchInput="searchInput"
								@toGetSearch="toGetSearch"
							/>
						</div>
					</div>
				</div>

				<!-- 1 -->
				<div class="plane-box">
					<div class="title-box">
						<TitleBox>
							<template #titlecont>
								<span class="label-link-txt" v-lang="{lang: controlSto.language, lgid: -126}">Ingredient</span>
								<!-- <span class="label-link-txt">-</span>
								<span v-lang="{lang: controlSto.language, lgid: -20}">Ingredient</span> -->
							</template>
						</TitleBox>

					</div>
					<div>
						<CombinationDiagram
							:dragramTypeList="dragramTypeList"
							@changeTabs="changeTabs"
							:selectTab="selectTab"
							:typeGraph="2"
							:dbData="dataGraph.dbData"
							:uiCodeDowm="uiCodeDowm"
							:dataTable="dataTable"
							:uiCode="uiCode"
							:templateList="dataTable.templateList"
							@toClkItem="toClkItem"
							:para="dataTable.para"
							:landNum="landNum"
							:condPage="condPage"
							@chgSize="chgSize"
							@chgCurrnt="chgCurrnt"
							:hotMapX="dataGraph.hotMapX"
							:hotMapY="dataGraph.hotMapY"
							:hotMapData="dataGraph.hotMapData"
							:loading="isLoading"
							:loadingNetWork="dataObj.loadingNetWork"
							:noDataFlag="dataObj.noDataFlag"
						/>
					</div>
				</div>
			</div>

		</div>

    </div>
</template>



<script setup>
    import { ref, reactive, computed, onBeforeMount, onMounted, nextTick, watch } from 'vue'
    import BreadCrumb from '@/components/BreadCrumb.vue'
    import SubmitBtn from '@/components/SubmitBtn.vue'
    import SearchDrop from '@/components/SearchDrop.vue'
    import uiTable from '@/components/ui-table.vue'
    import TitleBox from '@/components/TitleBox.vue'
		import CombinationDiagram from '@/components/combinationDiagram.vue'
		import { useRouter } from 'vue-router'

    import { controlStore } from '@/stores/control'
		import { nData } from '@/utils/datagraph'
		import { cloneDeep } from 'lodash';
    import { langTxt, getFilterThArr, getFilterLangArr } from '@/utils/util'
		import { getingreingrenetwork, getTableThList, ingreingreNetworkTable, ingrAll } from '@/service/tcm'


	const controlSto = controlStore();
	const router = useRouter();
	const selectTab = ref(0);
	const uiCodeDowm = ref('ingredient_To_Network');
	const landNum = ref(8);
	const isLoading = ref(false);
	const uiCode = ref('overall_network'); //下载表格的code
	const dataObj = reactive({
		crumbList: [
            {
								fkey: '-16',
                lable: 'Home',
                name: 'home'
            }, {
								fkey: '-126',
				// skey: '-20',
                lable: 'Ingredient-Ingredient',
                name: ''
            }
        ],
				targetNameObj: [],
				sourceNameObj: [],
				noDataFlag: true,
				loadingNetWork: false
	});
	let dataGraph = reactive({
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415,
			dbData: []
		});
		let condPage = reactive({
			pageSize: 10,
			pageNo: 1,
			total: 0
		})
		let dataTable = reactive({
			filterKey: 'ingreingre_netwrok',
			dTablevt: 1,
			tableConfig: {
				'tooltip-effect': 'dark',
				'highlight-current-row': true,
				stripe: true,
				'header-cell-style': { background: '#BC9F77', color: '#FFF' },
			},
			columnConfig: [],
			dataList: [],
			templateList: [{
					idField: '100716826576557300'
				}, 
				{
					idField: '100716826576557301'
				},
				{
					idField: '100716826576557302'
				},
				{
					idField: '100716826576557303'
				},
			],
			para: {
					langCode:controlSto.language == 1 ? 'ENG': 'CHN',
					// prescriptionId: detailId,
					uiTypeCode: uiCode,
					sourceName: dataObj.sourceNameObj,
					targetName: dataObj.targetNameObj
				}
		})
	let searchObjList = reactive({code: 'ingredient-ingr', searchObjArr: []})
	let searchObjOrigin = reactive({
		maxSize: 9,
		defaultSize: 2,
		combinateOringin: 'Ingredient',
		combinationTo: 'Ingredient',
		combinateOringinlgid: '-20',
		combinationTolgid: '-20',
		seachCon: '',
		opt: '1',
		id: '5',
		originData: [],
		targetData: [],
		originPlaceholder: '(-) -α-terpineol-8-O-β-D-glucopyranoside C16H28O6',
		targetPlaceholder: '(-) -α-terpineol-8-O-β-D-glucopyranoside C16H28O6'
	})

	
	const dragramTypeList = [
		{
			tname: 'Network',
			lgid: '-60',
			code: 'Network'
		}, {
			tname: 'Heatmap',
			lgid: '-61',
			code: 'Heatmap'
		}, {
			tname: 'Table',
			lgid: '-62',
			code: 'Table'
		}
	]
	const removeSearchCond = (item, index) => {
		if (index > 1) {
			searchObjList.searchObjArr.splice(index, 1)
		}
	}
	const addSearchCond = (item, index) => {
		searchObjList.searchObjArr.push(cloneDeep(searchObjOrigin))
	}
	const getSearchList = () => {
		  if(Object.values(searchObjOrigin).length !== 0) {
				for(let i = 0; i <= searchObjOrigin.defaultSize; i++) {
					searchObjOrigin.id = 'code_' + Math.random(9999) + Math.random(9999);
					searchObjList.searchObjArr.push(cloneDeep(searchObjOrigin))
				}
			}
	}
	const reset = () => {
		for(let v = 0; v < searchObjList.searchObjArr.length; v++) {
			searchObjList.searchObjArr[v].opt = '1';
			searchObjList.searchObjArr[v].seachCon = '';
		}
		dataObj.targetNameObj = [];
		dataObj.sourceNameObj = [];
		// searchResult();
		dataGraph = {
			data: [],
			links: [],
			diagramLenList: [],
			hotMapX: [],
			hotMapY: [],
			hotMapData: [],
			hotMaxRange: 2415,
			dbData: []
		}
		condPage = {
			pageSize: 10,
			pageNo: 1,
			total: 0
		}
		dataTable.dataList = [];
		dataTable.para.sourceName = {};
		dataTable.para.targetName = {};
	}
	onBeforeMount(()=> {
		getTableTh();
		getDataList();
		getSearchList();
		getIngrAll();
	});
	onMounted(()=>{
		if (router.currentRoute.value.query.sname) getIngrAll(router.currentRoute.value.query.sname, 0, 2);
		if (router.currentRoute.value.query.tname) getIngrAll(router.currentRoute.value.query.tname, 1, 2);
		// if (router.currentRoute.value.query.sname) searchObjList.searchObjArr[0].seachCon = router.currentRoute.value.query.sname;
		// if (router.currentRoute.value.query.tname) searchObjList.searchObjArr[1].seachCon = router.currentRoute.value.query.tname;
		searchResult();
	});
	const searchResult = () => {
		let targetNameArr = [], sourceNameArr = [];
		searchObjList.searchObjArr.forEach((e, index) => {
			if (index && e.seachCon && e.seachCode) {
				// targetNameObj[e.seachCode] = e.opt
				targetNameArr.push(e.seachCode)
			} else if (e.seachCode) {
				// sourceNameObj[e.seachCode] = e.opt
				sourceNameArr.push(e.seachCode)
			}
		})
		dataObj.targetNameObj = targetNameArr;
		dataObj.sourceNameObj = sourceNameArr.join(',');
		dataTable.para.sourceName = sourceNameArr.join(',');
		dataTable.para.targetName = targetNameArr;
		getDataList();
	}
	const changeTabs = (item, index) => {
		selectTab.value = index
	}
	const searchPlace = computed(() => {
		return langTxt(controlSto.language, '-15');
	});
	//table下载
	const toLoad = () => {

	}

	// -------1-----------------------------------------------------------------
	const searchInput = (name, index) => {
		getIngrAll(name, index, 1)
	}

	const toGetSearch = (code, name, index) => {
		searchObjList.searchObjArr[index].seachCon = name;
		searchObjList.searchObjArr[index].seachCode = code;
	}
	const getIngrAll = (name, index, type) => {
		ingrAll({langCode: controlSto.language == 1 ? 'ENG' : "CHN", name: name || ''}).then(res => {
			if(res.success && res.data) {
				if (type == 1) {
					searchObjList.searchObjArr[index].targetData = res.data;
					searchObjList.searchObjArr[index].originData = res.data;
				} else if(type == 2) {
					setTimeout(() => {
						searchObjList.searchObjArr[index].targetData = res.data;
						searchObjList.searchObjArr[index].originData = res.data;
					}, 400)
					searchObjList.searchObjArr[0].seachCon = router.currentRoute.value.query.sname;
					searchObjList.searchObjArr[1].seachCon = router.currentRoute.value.query.tname;
					res.data.forEach(e => {
						if(index && e.name == router.currentRoute.value.query.tname) {
							searchObjList.searchObjArr[index].seachCode = e.code;
						}
						if(!index && e.name == router.currentRoute.value.query.sname) {
							searchObjList.searchObjArr[index].seachCode = e.code;
						}
					})
					searchResult();
				} else{
					searchObjOrigin.originData = res.data || [];
					searchObjOrigin.targetData = res.data || [];
					searchObjList.searchObjArr.forEach(e => {
						e.targetData = res.data;
						e.originData = res.data;
					})
				}
				
			}
		})
	}

	const getTableTh = () => {
			getTableThList({
					uiCode: uiCode.value,
          langCode: 'ENG,CHN'
				}).then((res) => {
            isLoading.value = false;
            if (res.success) {
              let arr = res.data || [];
							let thArr = getFilterThArr(arr, dataTable.filterKey);
							let langArr = getFilterLangArr(thArr);
							controlSto.setLangList(langArr);
							dataTable.columnConfig = thArr;
							// console.log(dataTable.columnConfig, 'ataTable.columnConfig==')
            }
        }).catch(() => {
            isLoading.value = false;
        });
    };

    const getDataList = () => {
			if(dataObj.sourceNameObj.length == 0 || dataObj.targetNameObj.length == 0) return;
			dataObj.loadingNetWork = true;
			getingreingrenetwork({
				langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
				sourceName: dataObj.sourceNameObj,
				targetName: dataObj.targetNameObj,
				uiTypeCode: uiCode.value
			}).then(res => {
				const _res = res.data;
				if (_res.success && _res.data) {
					dataObj.loadingNetWork = false;
					if (_res.data.scatterDiagram) {
						const scatterDiagram = _res.data.scatterDiagram;
						if(scatterDiagram.nodeList.length == 0) dataObj.noDataFlag = true;
						else dataObj.noDataFlag = false;

						if (scatterDiagram.links && scatterDiagram.nodeList) {
							let arrXy = [], xyData = [];
							scatterDiagram.links.forEach(e => {
								e.lineStyle = {
									color: "#1677FF",
									width: 2
								}
							})
							dataGraph.dbData = {
								links: scatterDiagram.links,
								nodes: scatterDiagram.nodeList
							}
							scatterDiagram.nodeList.forEach(v => {
								arrXy.push(v.name)
							})
							//处理heatmap数据；
							let _arrXy = new Set(arrXy)
							arrXy = [..._arrXy]
							arrXy.forEach((ex, xind) => {
								arrXy.forEach((ey, yind) => {
									let id1 = '', id2 = '';
									scatterDiagram.nodeList.forEach((enode, nodeind) => {
										if(ex == enode.name) id1 = enode.id;
										if(ey == enode.name) id2 = enode.id;
										
									})
									if (id1 && id2){
										scatterDiagram.links.forEach((elink, linkInd)=> {
											if (id1 == elink.source && elink.target == id2) {
												xyData.push([xind, yind, Number(elink.distance)])
												id1 = '';
												id2 = '';
											}
										})
									}
								})
							});
							dataGraph.hotMapData = xyData;
							dataGraph.hotMapX = arrXy.reverse();
							dataGraph.hotMapY = arrXy;
							console.log(xyData, arrXy)
						}
						landNum.value = scatterDiagram.nodeList.length;
						
					}
					getTableData();
				}
			}).catch((err) => {
				dataObj.noDataFlag = true;
				dataObj.loadingNetWork = false;
			})
        
    };
		const getTableData = () => {
			isLoading.value = true;
			ingreingreNetworkTable({
				langCode: controlSto.language == 1 ? 'ENG' : 'CHN',
				sourceName: dataObj.sourceNameObj,
				targetName: dataObj.targetNameObj,
				uiTypeCode: uiCode.value,
				pageSize: condPage.pageSize,
				pageNo: condPage.pageNo
			}).then(res => {
				const _res = res.data;
				if (_res.success && _res.data && _res.data.records) {
					isLoading.value = false;
					dataTable.dataList = _res.data.records || [];
					condPage.total = _res.data.totalCount || 0;
				}
			}).catch(err => {
				isLoading.value = false;
			})
		}
		const chgSize = (e) => {
			condPage.pageSize = e || 10;
			getTableData();
		}
		const chgCurrnt = (e) => {
			condPage.pageNo = e || 1;
			getTableData();
		}

		const toClkItem = (rowItem, index) => {
			if (!index && index == 1) {
				//herb
				router.push({ name: 'herbdetail', query: {id: rowItem[dataTable.templateList[0].idField]} });
			} else {
				//成分
				router.push({ name: 'ingrdetail', query: {id: rowItem[dataTable.templateList[2].idField]} });
			}
		}
		
		watch(() => controlSto.language, (nv, ov) => {
			if(nv != ov) {
				getDataList();
				getTableData();
			}
		});

	
   
</script>

<style lang="scss" scoped>
	.ingringr-detail-page {
		height: 100%;
		min-height: calc(100vh - 250px);
		text-align: center;
		background-size: 100% 100%;
		.ingringr-cont {
			display: inline-block;
			// width: 1400px;
    		text-align: left;
			.title-box {
				padding-bottom: 32px;
			}
			.switch-box {
				padding-bottom: 32px;
				text-align: center;
				.switch-wrap {
					display: inline-block;
					border: 1px solid #BC9F77;
					border-radius: 30px;
					font-size: 0;
					color: #967846;
					.switch-item {
						display: inline-block;
						height: 40px;
						width: 200px;
						padding: 0 32px;
						line-height: 40px;
						border-right: 1px solid #BC9F77;
						font-weight: 600;
						font-size: 18px;
						cursor: pointer;
						&:first-child {
							// border-radius: 30px;
							border-top-left-radius: 16px;
							border-bottom-left-radius: 16px;
						}
						&:last-child {
							border-right: none;
							border-top-right-radius: 16px;
							border-bottom-right-radius: 16px;
						}
						&.switch-item-on {
							color: #fff;
							background-color: #BC9F77;
						}
					}
				}

			}
			.condition-box {
				// padding-bottom: 32px;
				.cond-item {
					margin-right: 16px;
				}
			}

			.cont-box {
				.plane-box {
					padding-top: 32px;
				}
			}



		}
	}
	
</style>




<style lang="scss">
    .cond-item-drop-box {
        .cond-drop-cont-wrap {
			max-height: 260px;
			overflow-y: auto;
			.cond-wrap {
				width: 188px;
				.cond-item-select {
					// width: 188px;
					padding: 8px 16px;
					margin-right: 0;
					font-size: 14px;
					font-weight: 400;
					border-bottom: 1px solid #ddd;
					cursor: pointer;
					&:last-child {
						border-bottom: none;
					}
				}
			}
        }
    }
</style>